//
//  MCChargeInRowViewCell.m
//  ERP
//
//  Created by QA on 15/11/5.
//  Copyright © 2015年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "MCChargeInRowViewCell.h"
#import "Charts-Swift.h"
#import "KLCPopup.h"

#import "MCChargeInDetailViewController.h"
#import "NSDictionary+DataFormat.h"
#import "MCChargeInChartViewCell.h"

#import "MNReportView.h"
#import "KWFormViewQuickBuilder.h"

@interface MCChargeInRowViewCell()<ChartViewDelegate>

@property (nonatomic, strong) PieChartView *chartView;
@property (nonatomic, strong) UINavigationController *navigationController;
@property (nonatomic, strong) NSIndexPath* indexPath;
@property (nonatomic, strong) NSArray *arrayData;

@property (strong, nonatomic) NSString *searchStartTime;
@property (strong, nonatomic) NSString *searchEndTime;

@property (nonatomic, strong) UIButton *subLable;

@end

@implementation MCChargeInRowViewCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
//        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"MCChargeInRowViewCell" owner:self options:nil];
//        self = [topLevelObjects objectAtIndex:0];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        [self materialChargeInCell];
    }
    return self;
}

- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)setNavigationController:(UINavigationController*)navigationController indexPath:(NSIndexPath*)indexPath
{
    self.navigationController = navigationController;
    self.indexPath = indexPath;
}

- (void)setSearchStartTime:(NSString *)startTime endTime:(NSString*)endTime
{
    //保存时间数据
    self.searchStartTime = startTime;
    self.searchEndTime = endTime;
    
    NSString *startTime1 = [self.searchStartTime stringByReplacingOccurrencesOfString:@"-" withString:@"."];
    NSString *endTime1 = [self.searchEndTime stringByReplacingOccurrencesOfString:@"-" withString:@"."];
    
    NSString *showString = [NSString stringWithFormat:@"以下为%@-%@数据  明细",startTime1,endTime1];
    NSMutableAttributedString *lableText = [[NSMutableAttributedString alloc] initWithString:showString];
    [lableText addAttributes:@{NSUnderlineStyleAttributeName:[NSNumber numberWithInt:NSUnderlineStyleSingle],
                               NSForegroundColorAttributeName: [UIColor colorWithRed:51/255.f green:181/255.f blue:229/255.f alpha:1.f] } range:NSMakeRange(lableText.length - 2, 2)];
    [self.subLable setAttributedTitle:lableText forState:UIControlStateNormal];
}

- (void)setChartViewAnimated
{
    if (_chartView)
    [_chartView animateWithXAxisDuration:1.5 yAxisDuration:1.5 easingOption:ChartEasingOptionEaseOutBack];
}

- (void)materialChargeInCell
{
    //绘制标题
    UILabel *titleLable = [[UILabel alloc] initWithFrame:CGRectMake(20, 15, SuperWidth - 40, 22)];
    titleLable.text = @"原材进料统计分析(吨)";
    titleLable.font = [UIFont systemFontOfSize:16];
    titleLable.textAlignment = NSTextAlignmentCenter;
    [self.contentView addSubview:titleLable];
    
    //绘制标题
    UIButton *subLable = [[UIButton alloc] initWithFrame:CGRectMake(20, 30, SuperWidth - 40, 32)];
    subLable.titleLabel.textColor = [UIColor darkGrayColor];
    [subLable setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    subLable.titleLabel.font = [UIFont systemFontOfSize:13];
    [self.contentView addSubview:subLable];
    subLable.userInteractionEnabled = YES;
    self.subLable = subLable;
    
    self.chartView = [[PieChartView alloc] initWithFrame:CGRectMake(0, 48, SuperWidth, 260.0)];
    _chartView.delegate = self;
    _chartView.usePercentValuesEnabled = YES;
//    _chartView.holeTransparent = YES;
//    _chartView.isZoomTapGestureReduction = YES;
//    _chartView.holeRadiusPercent = 0.38;
//    _chartView.transparentCircleRadiusPercent = 0.40;
    _chartView.holeRadiusPercent = 0.0;
    _chartView.transparentCircleRadiusPercent = 0.0;
//    _chartView.descriptionText = @"";
    _chartView.noDataText = @"";
    [_chartView setExtraOffsetsWithLeft:5.f top:10.f right:5.f bottom:5.f];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
    paragraphStyle.alignment = NSTextAlignmentCenter;
    
    _chartView.drawCenterTextEnabled = NO;
    _chartView.drawHoleEnabled = YES;
    _chartView.rotationAngle = 0.0;
    _chartView.rotationEnabled = YES;
    _chartView.highlightPerTapEnabled = YES;
    _chartView.usePercentValuesEnabled = NO;
    
    ChartLegend *l = _chartView.legend;
    l.horizontalAlignment = ChartLegendHorizontalAlignmentRight;
    l.verticalAlignment = ChartLegendVerticalAlignmentTop;
    l.orientation = ChartLegendOrientationVertical;
    l.xEntrySpace = 7.0;
    l.yEntrySpace = 0.0;
    l.yOffset = 0.0;
    l.formLineWidth = 100;
    [self.contentView addSubview:_chartView];
}

//材料
- (void)setMaterialData:(NSArray *)dataArray
{
    self.arrayData = dataArray;
    [_subLable addTarget:self action:@selector(changeSelector:) forControlEvents:UIControlEventTouchUpInside];
    
    // IMPORTANT: In a PieChart, no values (Entry) should have the same xIndex (even if from different DataSets), since no values can be drawn above each other.
    NSMutableArray *yVals1 = [[NSMutableArray alloc] init];
    for (int i = 0; i < dataArray.count; i++)
    {
        NSDictionary *mDictionary = [dataArray objectAtIndex:i];
        NSString *lable = [mDictionary objectFormatStringForKey:@"材料名称" defaults:@"未知"];
        CGFloat value = [mDictionary objectFormatFloatForKey:@"打印净重" retain:1 except:0];
        [yVals1 addObject:[[PieChartDataEntry alloc] initWithValue:value label:lable]];
    }
    
    if(yVals1.count <= 0) [yVals1 addObject:[[PieChartDataEntry alloc] initWithValue:0.01 label:@"无材料名称"]];
    
    PieChartDataSet *dataSet = [[PieChartDataSet alloc] initWithValues:yVals1 label:@"原材种类"];
    dataSet.sliceSpace = 2.0;
    
    // add a lot of colors
    NSMutableArray *colors = [[NSMutableArray alloc] init];
    [colors addObjectsFromArray:ChartColorTemplates.joyful];
    [colors addObjectsFromArray:ChartColorTemplates.vordiplom];
    [colors addObjectsFromArray:ChartColorTemplates.colorful];
    [colors addObjectsFromArray:ChartColorTemplates.liberty];
    [colors addObjectsFromArray:ChartColorTemplates.pastel];
    [colors addObject:[UIColor colorWithRed:51/255.f green:181/255.f blue:229/255.f alpha:1.f]];
    dataSet.colors = colors;
    
    NSNumberFormatter *pFormatter = [[NSNumberFormatter alloc] init];
    pFormatter.numberStyle = NSNumberFormatterPercentStyle;
    pFormatter.maximumFractionDigits = 1;
    pFormatter.multiplier = @1.f;
    pFormatter.percentSymbol = @"t";
    
    PieChartData *data = [[PieChartData alloc] initWithDataSet:dataSet];
    [data setValueFormatter:[[ChartDefaultValueFormatter alloc] initWithFormatter:pFormatter]];
    [data setValueFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:11.f]];
    [data setValueTextColor:UIColor.whiteColor];
    
    self.chartView.data = data;
    [self.chartView highlightValues:nil];
}

//供应商
- (void)setSupplierData:(NSArray *)dataArray
{
    self.arrayData = dataArray;
    [_subLable addTarget:self action:@selector(changeSuppliersSelector:) forControlEvents:UIControlEventTouchUpInside];
    
    // IMPORTANT: In a PieChart, no values (Entry) should have the same xIndex (even if from different DataSets), since no values can be drawn above each other.
    NSMutableArray *yVals1 = [[NSMutableArray alloc] init];
    for (int i = 0; i < dataArray.count; i++)
    {
        NSDictionary *mDictionary = [dataArray objectAtIndex:i];
        NSString *label = [mDictionary objectFormatStringForKey:@"供应商" defaults:@"未知"];
        CGFloat value = [mDictionary objectFormatFloatForKey:@"打印净重" retain:1 except:0];
        [yVals1 addObject:[[PieChartDataEntry alloc] initWithValue:value label:label]];
    }
    
    PieChartDataSet *dataSet = [[PieChartDataSet alloc] initWithValues:yVals1 label:@"原材供应商"];
    dataSet.sliceSpace = 2.0;
    
    // add a lot of colors
    NSMutableArray *colors = [[NSMutableArray alloc] init];
    [colors addObjectsFromArray:ChartColorTemplates.joyful];
    [colors addObjectsFromArray:ChartColorTemplates.vordiplom];
    [colors addObjectsFromArray:ChartColorTemplates.colorful];
    [colors addObjectsFromArray:ChartColorTemplates.liberty];
    [colors addObjectsFromArray:ChartColorTemplates.pastel];
    [colors addObject:[UIColor colorWithRed:51/255.f green:181/255.f blue:229/255.f alpha:1.f]];
    dataSet.colors = colors;
    
    NSNumberFormatter *pFormatter = [[NSNumberFormatter alloc] init];
    pFormatter.numberStyle = NSNumberFormatterPercentStyle;
    pFormatter.maximumFractionDigits = 1;
    pFormatter.multiplier = @1.f;
    pFormatter.percentSymbol = @"t";
    
    PieChartData *data = [[PieChartData alloc] initWithDataSet:dataSet];
    [data setValueFormatter:[[ChartDefaultValueFormatter alloc] initWithFormatter:pFormatter]];
    [data setValueFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:11.f]];
    [data setValueTextColor:UIColor.whiteColor];
    
    [self.chartView highlightValues:nil];
    self.chartView.data = data;
}

#pragma mark ChartViewDelegate

- (void)chartValueSelected:(ChartViewBase *)chartView entry:(ChartDataEntry *)entry highlight:(ChartHighlight *)highlight
{
    if (!self.navigationController) return;
    if(self.arrayData && self.arrayData.count <=0) return;
    
    NSDictionary *mDictionary = [self.arrayData objectAtIndex:highlight.x];
    NSArray *valueArray = @[_searchStartTime, _searchEndTime, mDictionary];
    
    MCChargeInDetailViewController *viewController = [[MCChargeInDetailViewController alloc] initWithValue:valueArray];
    [self.navigationController pushViewController:viewController animated:YES];
}


#pragma mark
#pragma mark - IBAction

//供应商明细
- (void)changeSuppliersSelector:(id)sender
{
    NSArray *titles = @[@"供应商",@"打印净重",@"金额"];
    
    KWFormViewQuickBuilder *builder = [[KWFormViewQuickBuilder alloc] init];
    [builder setBorderColor:[UIColor colorWithWhite:0.9 alpha:1.0]];
    [builder addRecord:titles];
    
    for(NSDictionary *dic in self.arrayData){
        NSString *ckwz = [dic objectFormatStringForKey:@"供应商" defaults:@"-"];
        NSString *zdsl = [dic objectFormatFloatStringForKey:@"打印净重" retain:1 format:@"%@"];;
        NSString *sysl = [dic objectFormatFloatStringForKey:@"金额" retain:2 format:@"%@"];;
        [builder addRecord:@[ckwz,zdsl,sysl]];
    }
    
    CGFloat itemWidth = SuperWidth/18;
    NSNumber *value1 = [NSNumber numberWithFloat:(itemWidth*7)];
    NSNumber *value2 = [NSNumber numberWithFloat:(itemWidth*5)];
    NSNumber *value3 = [NSNumber numberWithFloat:(itemWidth*5)];
    
    UIView *view = [[UIView alloc] init];
    
    //绘制标题
    UILabel *titleLable = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, SuperWidth - 40, 30)];
    titleLable.text = @"原材进料统计明细(吨)";
    titleLable.font = [UIFont boldSystemFontOfSize:20];
    titleLable.textAlignment = NSTextAlignmentCenter;
    titleLable.textColor = [UIColor colorWithWhite:1.0 alpha:0.85];
    [view addSubview:titleLable];
    
    KWFormView *formView = [builder startCreatWithWidths:@[value1,value2,value3] startPoint:CGPointMake(0, 0)];
    formView.mKWFormViewHeight = 38;
    formView.layer.cornerRadius = 3;
    formView.layer.masksToBounds = YES;
    
    CGRect frame = formView.frame;
    frame.origin.y = 50;
    formView.frame = frame;
    [view addSubview:formView];
    view.frame = CGRectMake(0, 0, formView.bounds.size.width, formView.bounds.size.height + 40);
    
    KLCPopupLayout layout = KLCPopupLayoutMake(KLCPopupHorizontalLayoutCenter, KLCPopupVerticalLayoutCenter);
    KLCPopup* popup = [KLCPopup popupWithContentView:view
                                            showType:KLCPopupShowTypeGrowIn
                                         dismissType:KLCPopupDismissTypeShrinkOut
                                            maskType:KLCPopupMaskTypeDimmed
                            dismissOnBackgroundTouch:YES
                               dismissOnContentTouch:NO];
    [popup showWithTMLayout:layout];
}

//材料明细
- (void)changeSelector:(id)sender
{
    NSArray *titles = @[@"材料名称",@"当前价格",@"平均价格",@"打印净重",@"金额"];
    
    KWFormViewQuickBuilder *builder = [[KWFormViewQuickBuilder alloc] init];
    [builder setBorderColor:[UIColor colorWithWhite:0.9 alpha:1.0]];
    [builder addRecord:titles];
    
    for(NSDictionary *dic in self.arrayData){
        NSString *ckwz = [dic objectFormatStringForKey:@"材料名称" defaults:@"-"];
        NSString *pm = [dic objectFormatFloatStringForKey:@"当前价格" retain:2 format:@"%@"];;
        NSString *gg = [dic objectFormatFloatStringForKey:@"平均价格" retain:2 format:@"%@"];;
        NSString *zdsl = [dic objectFormatFloatStringForKey:@"打印净重" retain:1 format:@"%@"];;
        NSString *sysl = [dic objectFormatFloatStringForKey:@"金额" retain:2 format:@"%@"];;
        [builder addRecord:@[ckwz,pm,gg,zdsl,sysl]];
    }
    
    CGFloat itemWidth = SuperWidth/32;
    NSNumber *value1 = [NSNumber numberWithFloat:(itemWidth*10)];
    NSNumber *value2 = [NSNumber numberWithFloat:(itemWidth*5)];
    NSNumber *value3 = [NSNumber numberWithFloat:(itemWidth*5)];
    NSNumber *value4 = [NSNumber numberWithFloat:(itemWidth*5)];
    NSNumber *value5 = [NSNumber numberWithFloat:(itemWidth*5)];
    
    UIView *view = [[UIView alloc] init];
    
    //绘制标题
    UILabel *titleLable = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, SuperWidth - 40, 30)];
    titleLable.text = @"原材进料统计明细(吨)";
    titleLable.font = [UIFont boldSystemFontOfSize:20];
    titleLable.textAlignment = NSTextAlignmentCenter;
    titleLable.textColor = [UIColor colorWithWhite:1.0 alpha:0.85];
    [view addSubview:titleLable];
    
    KWFormView *formView = [builder startCreatWithWidths:@[value1,value2,value3,value4,value5] startPoint:CGPointMake(0, 0)];
    formView.mKWFormViewHeight = 38;
    formView.layer.cornerRadius = 3;
    formView.layer.masksToBounds = YES;
    
    CGRect frame = formView.frame;
    frame.origin.y = 50;
    formView.frame = frame;
    [view addSubview:formView];
    view.frame = CGRectMake(0, 0, formView.bounds.size.width, formView.bounds.size.height + 40);
    
    KLCPopupLayout layout = KLCPopupLayoutMake(KLCPopupHorizontalLayoutCenter, KLCPopupVerticalLayoutCenter);
    KLCPopup* popup = [KLCPopup popupWithContentView:view
                                            showType:KLCPopupShowTypeGrowIn
                                         dismissType:KLCPopupDismissTypeShrinkOut
                                            maskType:KLCPopupMaskTypeDimmed
                            dismissOnBackgroundTouch:YES
                               dismissOnContentTouch:NO];
    [popup showWithTMLayout:layout];
}

@end
